/**
* All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
*
* MmsSensitiveThesaurusService
* 敏感词库
*
* 修改纪录
* 2022-02-22 版本：1.0 hudeyong 创建。
* @version 版本：1.0
* @author 作者：hudeyong
* 创建日期：2022-02-22
*/
package com.topscomm.mms.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.serializer.DateCodec;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.IBasicService;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.service.ICboItemsService;
import com.topscomm.mms.pojo.MmsSensitiveThesaurusEntity;
import com.topscomm.mms.service.IMmsSensitiveThesaurusService;
import com.topscomm.mms.service.impl.auto.MmsSensitiveThesaurusServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.RedisDatacodeStore;
import com.topscomm.tap.common.RedisMmsStore;

@Service(value = "mmsSensitiveThesaurusService")
@Scope(value = "singleton")
public class MmsSensitiveThesaurusService extends MmsSensitiveThesaurusServiceAuto implements IMmsSensitiveThesaurusService {
    /**
     * 敏感词匹配规则
     */
    public static final int MinMatchTYpe = 1;      //最小匹配规则，如：敏感词库["中国","中国人"]，语句："我是中国人"，匹配结果：我是[中国]人
    public static final int MaxMatchType = 2;      //最大匹配规则，如：敏感词库["中国","中国人"]，语句："我是中国人"，匹配结果：我是[中国人]
    /**
     * 敏感词集合
     */
    protected static HashMap sensitiveWordMap;

	/**
	 * @param map
	 * @return
	 * @description:批量新增
	 * @author: hdy
	 * @date: 2022年04月11日
	 * @modify:
	 */
	@Override
	public void doSave(Map<String, Object> paraMap) {
		// TODO Auto-generated method stub
		List<Map<String, Object>> sensitiveList = (List<Map<String, Object>>) paraMap.get("sensitiveList");
		List<BasicEntity> thesaurusEntities = new ArrayList<BasicEntity>();
		for(Map<String, Object> map :  sensitiveList) {
			MmsSensitiveThesaurusEntity thesaurusEntity  = new MmsSensitiveThesaurusEntity();
			thesaurusEntity.setWord(ConvertUtil.convertToString(map.get("word")));
			thesaurusEntity.setType(ConvertUtil.convertToString(map.get("type")));
			thesaurusEntity.setRangesys(ConvertUtil.convertToString(map.get("rangesys")));
			thesaurusEntity.setEnabled(ConvertUtil.convertToInt(map.get("enabled")));
			long[] arrayId = PrimaryKeyUtil.GeneIDs(thesaurusEntity.getTableName(), 1);
			thesaurusEntity.setId(arrayId[0]);
			thesaurusEntities.add(thesaurusEntity);
		}
		this.insertBatch(thesaurusEntities);
	}

	/**
	 * @param map
	 * @return
	 * @description:敏感词检测
	 * @author: hdy
	 * @date: 2022年04月11日
	 * @modify:
	 */
    public Map<String, Object> mainSensitiveWord(String inputvalue) {
        Set<String> sensitiveWordSet = new HashSet<>();
        StringBufferProxy sql = new StringBufferProxy();
        MmsSensitiveThesaurusService mmsSensitiveThesaurusService= (MmsSensitiveThesaurusService) SpringUtil.getBean("mmsSensitiveThesaurusService");
        sql.appendSingle("TYPE = '1' AND RANGESYS ='1' AND ENABLED = 1");
        List<String> filedList = new ArrayList<String>();
        filedList.add("word as word");
        List<Map<String, Object>> sensitiveList = mmsSensitiveThesaurusService.queryMapFieldsByWhere(sql.toString(),filedList);
        for(Map<String, Object> map : sensitiveList) {
        	sensitiveWordSet.add(ConvertUtil.convertToString(map.get("word")));
        }
        //初始化敏感词库
        this.init(sensitiveWordSet);
        //是否含有关键字
        boolean result = this.contains(inputvalue);
        //result = this.contains(inputvalue, this.MinMatchTYpe);
        //获取语句中的敏感词，使用最大匹配规则。
        Set<String> set = this.getSensitiveWord(inputvalue);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", result);
        resultMap.put("sensitiveWord", set);
        //set = this.getSensitiveWord(inputvalue, SensitiveWordUtil.MinMatchTYpe);
		return resultMap;
    }

    /**
     * 初始化敏感词库，构建DFA算法模型
     *
     * @param sensitiveWordSet 敏感词库
     */
    public synchronized void init(Set<String> sensitiveWordSet) {
        initSensitiveWordMap(sensitiveWordSet);
    }

    /**
     * 初始化敏感词库，构建DFA算法模型
     *
     * @param sensitiveWordSet 敏感词库
     */
    private void initSensitiveWordMap(Set<String> sensitiveWordSet) {
        //初始化敏感词容器，减少扩容操作
        sensitiveWordMap = new HashMap(sensitiveWordSet.size());
        String key;
        Map nowMap;
        Map<String, String> newWorMap;
        //迭代sensitiveWordSet
        Iterator<String> iterator = sensitiveWordSet.iterator();
        while (iterator.hasNext()) {
            //关键字
            key = iterator.next();
            nowMap = sensitiveWordMap;
            for (int i = 0; i < key.length(); i++) {
                //转换成char型
                char keyChar = key.charAt(i);
                //库中获取关键字
                Object wordMap = nowMap.get(keyChar);
                //如果存在该key，直接赋值，用于下一个循环获取
                if (wordMap != null) {
                    nowMap = (Map) wordMap;
                } else {
                    //不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
                    newWorMap = new HashMap<>();
                    //不是最后一个
                    newWorMap.put("isEnd", "0");
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }

                if (i == key.length() - 1) {
                    //最后一个
                    nowMap.put("isEnd", "1");
                }
            }
        }
    }

    /**
     * 判断文字是否包含敏感字符
     *
     * @param txt       文字
     * @param matchType 匹配规则 1：最小匹配规则，2：最大匹配规则
     * @return 若包含返回true，否则返回false
     */
    public boolean contains(String txt, int matchType) {
        boolean flag = false;
        for (int i = 0; i < txt.length(); i++) {
            int matchFlag = checkSensitiveWord(txt, i, matchType); //判断是否包含敏感字符
            if (matchFlag > 0) {    //大于0存在，返回true
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 判断文字是否包含敏感字符
     *
     * @param txt 文字
     * @return 若包含返回true，否则返回false
     */
    public boolean contains(String txt) {
        return contains(txt, MaxMatchType);
    }

    /**
     * 获取文字中的敏感词
     *
     * @param txt       文字
     * @param matchType 匹配规则 1：最小匹配规则，2：最大匹配规则
     * @return
     */
    public Set<String> getSensitiveWord(String txt, int matchType) {
        Set<String> sensitiveWordList = new HashSet<>();

        for (int i = 0; i < txt.length(); i++) {
            //判断是否包含敏感字符
            int length = checkSensitiveWord(txt, i, matchType);
            if (length > 0) {//存在,加入list中
                sensitiveWordList.add(txt.substring(i, i + length));
                i = i + length - 1;//减1的原因，是因为for会自增
            }
        }

        return sensitiveWordList;
    }

    /**
     * 获取文字中的敏感词
     *
     * @param txt 文字
     * @return
     */
    public Set<String> getSensitiveWord(String txt) {
        return getSensitiveWord(txt, MaxMatchType);
    }

    /**
     * 检查文字中是否包含敏感字符，检查规则如下：<br>
     *
     * @param txt
     * @param beginIndex
     * @param matchType
     * @return 如果存在，则返回敏感词字符的长度，不存在返回0
     */
    private int checkSensitiveWord(String txt, int beginIndex, int matchType) {
        //敏感词结束标识位：用于敏感词只有1位的情况
        boolean flag = false;
        //匹配标识数默认为0
        int matchFlag = 0;
        char word;
        Map nowMap = sensitiveWordMap;
        for (int i = beginIndex; i < txt.length(); i++) {
            word = txt.charAt(i);
            //获取指定key
            nowMap = (Map) nowMap.get(word);
            if (nowMap != null) {//存在，则判断是否为最后一个
                //找到相应key，匹配标识+1
                matchFlag++;
                //如果为最后一个匹配规则,结束循环，返回匹配标识数
                if ("1".equals(nowMap.get("isEnd"))) {
                    //结束标志位为true
                    flag = true;
                    //最小规则，直接返回,最大规则还需继续查找
                    if (MinMatchTYpe == matchType) {
                        break;
                    }
                }
            } else {//不存在，直接返回
                break;
            }
        }
        if (matchFlag < 2 || !flag) {//长度必须大于等于1，为词
            matchFlag = 0;
        }
        return matchFlag;
    }

}
